package com.zxt.web.controller;

import com.alibaba.fastjson.JSON;
import com.zxt.domain.GoodsType;
import com.zxt.service.GoodsTypeService;
import com.zxt.service.impl.GoodsTypeServletImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * projectName:myXiaoMi
 * author:ZhangXiaoTeng
 * time:2021/12/6 11:56
 * description:
 */
@WebServlet("/goodstypeservlet")
public class GoodsTypeServlet extends BaseServlet{

    public String goodstypelist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");

        ServletContext application=this.getServletContext();
        String goodType=(String)application.getAttribute("goodsTypes");
        if (goodType!=null){
            response.getWriter().write(goodType);
            System.out.println("从application中获取的");
            return null;
        }
        //1.调用业务逻辑
        GoodsTypeService goodsTypeService = new GoodsTypeServletImpl();
        //2.调用方法
        List<GoodsType> goodsTypes = goodsTypeService.findByLevel(1);
        System.out.println("从数据库中获取");
        //3.把集合转json字符串
        String json = JSON.toJSONString(goodsTypes);
        //4.返回json字符串
        response.getWriter().write(json);
        //5.把json放入application中
        application.setAttribute("goodsTypes",json);
        return null;
    }
}

